package com.albert.eurekaconsumer.controller;

import com.albert.eurekaconsumer.model.UserInfo;
import com.albert.eurekaconsumer.service.IUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TestController {
    private final static Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    IUserInfoService userInfoService;

    @RequestMapping(value = "/test")
    public String test() {
        String url = "http://eureka-producer/hello?name=zhanglifeng";
        String result = restTemplate.getForObject(url, String.class);
        logger.info("/test get request ,url={} , res ={} ",url, result);
        return result;
    }

    @RequestMapping(value = "/testpost")
    public String testPost() {
        Map<String, Object> map = new HashMap();
        map.put("name", "zhanglifeng");
        map.put("age", 30);
        String url = "http://eureka-producer/gogogo";
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, map, String.class);
        logger.info("testpost receive req, url ={} ,data={} ,result = {} ", url, map, responseEntity.getBody());
        return responseEntity.getBody();
    }

    @RequestMapping(value = "adduser")
    public String add(@RequestBody UserInfo userInfo) {
        UserInfo u = userInfoService.queryUserbyLoginName(userInfo.getLoginName());
        if (u != null) {
            return "用户已经存在，不能添加！";
        }
        return userInfoService.add(userInfo);
    }
}
